package com.cjack.frenchexcel.util;

import cn.hutool.core.io.FileUtil;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfWriter;
import org.apache.pdfbox.io.MemoryUsageSetting;
import org.apache.pdfbox.multipdf.PDFMergerUtility;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;

import javax.imageio.ImageIO;
import java.awt.color.ColorSpace;
import java.awt.image.BufferedImage;
import java.awt.image.ColorConvertOp;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class PdfUtil {

    /**
     * @return
     * @Author Ragty
     * @Description 将图片转换为PDF
     * @Date 15:27 2019/3/4
     **/
    private static String Img2PDF(String imagePath, BufferedImage img, String descfolder) throws Exception {
        String pdfPath = "";
        try {
            //图片操作
            Image image = null;
            File file = new File(descfolder);
            if (!file.exists()) {
                file.mkdirs();
            }
            pdfPath = descfolder + "/" + System.currentTimeMillis() + ".pdf";
            String type = imagePath.substring(imagePath.lastIndexOf(".") + 1);

            image = Image.getInstance(imagePath);
            float imgHeight = image.getHeight();
            float imgWidth = image.getWidth();
            Document doc = new Document(new Rectangle(imgWidth, imgHeight), 0f, 0f, 0f, 0f);/*
            float documentHeight;
            float documentWidth;
            if( imgHeight/imgWidth > doc.getPageSize().getHeight()/doc.getPageSize().getWidth()){
                //按照高来计算宽
                documentHeight = doc.getPageSize().getHeight();
                documentWidth = documentHeight * ( imgHeight/imgWidth);
            }else{
                //按照宽来计算高
                documentWidth = doc.getPageSize().getWidth();
                documentHeight = documentWidth * ( imgWidth/imgHeight);
            }
            image.scaleAbsolute( documentWidth, documentHeight);//重新设置宽高 */
            FileOutputStream fos = new FileOutputStream(pdfPath);
            PdfWriter.getInstance(doc, fos);
            doc.open();
            doc.add(image);
            doc.close();/*
            //更换图片图层
            BufferedImage bufferedImage = new BufferedImage(img.getWidth(), img.getHeight(),BufferedImage.TYPE_3BYTE_BGR);
            bufferedImage.getGraphics().drawImage(img, 0,0, img.getWidth(), img.getHeight(), null);
            bufferedImage=new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_GRAY),null).filter (bufferedImage,null);
            //图片流处理
            doc.setPageSize(new Rectangle(bufferedImage.getWidth(), bufferedImage.getHeight()));
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            boolean flag = ImageIO.write(bufferedImage, type, out);
            byte[] b = out.toByteArray();
            image = Image.getInstance(b);
            FileOutputStream fos = new FileOutputStream(pdfPath);
            PdfWriter.getInstance(doc, fos);
            doc.open();
            doc.add(image);
            doc.close();*/
        } catch (BadElementException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return pdfPath;
    }

    /**
     * @return
     * @Author Ragty
     * @Description 合成PDF
     * @Date 17:25 2019/3/7
     **/
    public static void mergePDF(String[] pdfs, String finalPdfPath) throws Exception {
        PDFMergerUtility mergePdf = new PDFMergerUtility();
        for (String file : pdfs) {
            //if (file.toLowerCase().endsWith("pdf")) {
                mergePdf.addSource(file);
            //}
        }
        mergePdf.setDestinationFileName(finalPdfPath);
        // 合并pdf
        mergePdf.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());
        System.out.println("merge over");
    }

    /**
     * 将多张图片合成到一个pdf里面
     *
     * @param imgs    多张图片的路径
     * @param pdfPath 最终生成的pdf的路径
     * @return
     */
    public static void mergeImgsToPdf(String[] imgs, String pdfPath, String baseServerDir) throws Exception {
        String pdfsTempDir = baseServerDir + System.currentTimeMillis();//合成的时候，生成的中间pdf保存目录，等合成测地完成之后，需要将这个目录删除
        String[] pdfFiles = new String[imgs.length];
        for (int i = 0; i < imgs.length; i++) {
            String img = imgs[i];
            BufferedImage bi = ImgUtil.rotateImage(img);
            String pdffile = Img2PDF(img, bi, pdfsTempDir);
            pdfFiles[i] = pdffile;
        }
        mergePDF(pdfFiles, pdfPath);
        //删除临时保存pdf的目录
        FileUtils.delDir(pdfsTempDir);
    }

    public static void pdfToImagePath(String pdfPath, String imgPath) {
        File file = new File(pdfPath);
        try {
            PDDocument doc = PDDocument.load(file);
            PDFRenderer renderer = new PDFRenderer(doc);
            int pageCount = doc.getNumberOfPages();
            for (int i = 0; i < pageCount; i++) {
                // 方式2,第二个参数是设置缩放比(即像素),参数越大生成图片分辨率越高，转换时间也就越长
                BufferedImage image = renderer.renderImage(i, 1.00f);
                ImageIO.write(image, "jpg", new File(imgPath));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception {
        String pdfPath = "/opt/frenchProjectFile//sellInvoice/2020-02-27/7b73ddf0-c4b1-4071-b820-64c425e3ee0e.pdf";
        String imgPath = "/home/timanetworks/Icoopa.jpg";
        pdfToImagePath(pdfPath, imgPath);
    }
}
